﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Reflection;

namespace WPFClient.Codes
{
    /// <summary>
    /// 配置文件帮助类
    /// </summary>
    public static class ConfigHelper
    {
        public static JObject AppConfig { get; private set; }

        static ConfigHelper()
        {
            AppConfig = InitConfig();
        }

        /// <summary>
        /// <summary>
        /// 初始化配置文件
        /// </summary>
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static JObject InitConfig()
        {
            JObject jsonObject = null;

            try
            {
                // 获取配置文件路径
                string assemblyLocation = Assembly.GetExecutingAssembly().Location;
                string appDirectory = Path.GetDirectoryName(assemblyLocation);
                string configPath = Path.Combine(appDirectory, "AppConfig.json");

                if (!File.Exists(configPath))
                {
                    throw new FileNotFoundException($"配置文件未找到: {configPath}。请确保AppConfig.json文件存在于应用程序目录中。");
                }

                // 读取并解析JSON
                string jsonContent = File.ReadAllText(configPath);
                jsonObject = JObject.Parse(jsonContent);
            }
            catch (Exception ex)
            {
                throw new Exception($"读取配置失败: {ex.Message}", ex);
            }

            return jsonObject;
        }

        /// <summary>
        /// 使用 JSONPath 读取配置值
        /// </summary>
        /// <param name="jsonPath">$.PLC1.PLC1.IP</param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static string GetConfigValue(string jsonPath,string defaultValue = "")
        {
            if (AppConfig == null)
                throw new InvalidOperationException("配置未初始化");

            JToken token = AppConfig.SelectToken(jsonPath);
            string value = token?.ToString();

            return string.IsNullOrEmpty(value) ? defaultValue : value;
        }
    }
}